package com.bingsum.controller;

import java.util.HashMap;
import java.util.Map;

import com.bingsum.model.User;
import com.bingsum.service.UserService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import com.bingsum.util.HttpClientUtil;
import com.bingsum.util.IMoocJSONResult;
import com.bingsum.util.JsonUtils;
import com.bingsum.wx.mp.config.WxMpConfiguration;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import com.bingsum.model.WXSessionModel;

@RestController
@RequestMapping("/api")
public class WXLoginController {
	@Autowired
	private UserService userService;

	public String wx(String code) {
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		Map<String, String> param = new HashMap<>();
		param.put("appid", "wxc6cc463dd8652f2c");
		param.put("secret", "d7f43cf32be216fe94a55d7d0a4c0f3d");
		param.put("js_code", code);
		param.put("grant_type", "authorization_code");

		String wxResult = HttpClientUtil.doGet(url, param);
		System.out.println(wxResult);
		return wxResult;
	}

	@RequestMapping(value="/user/wxLogin",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public IMoocJSONResult wxLogin(@RequestBody String json){

		User user = new User();
		try {
			JSONObject Obtain = new JSONObject(json);
			String code = Obtain.get("code").toString();

			String result = wx(code);

			JSONObject Obtain_id = new JSONObject(result);
			System.out.println("json："+Obtain_id);
			System.out.println("openid: " + Obtain_id.get("openid"));		//openid 取到值
			/*参数获取开始*/
			String open_id = Obtain_id.get("openid").toString();
			String nick_name = Obtain.get("nickName").toString();
			String avatar_url = Obtain.get("avatarUrl").toString();
			/*参数获取结束*/
			user = userService.getUserInfo(open_id);
			if (user == null){
				System.out.println("新用户");
				User use = new User();
				use.setNick_name(nick_name);
				use.setAvatar_url(avatar_url);
				use.setOpen_id(open_id);
				System.out.println("user:"+use.toString());
				int flag = userService.addUserInfo(use);
				System.out.println("flag======================================================="+flag);
				if (flag>0){
					System.out.println("成功");
					return IMoocJSONResult.ok(use.getOpen_id());
				}else{
					return IMoocJSONResult.errorMsg("新增失败");
				}
			}else{
				return IMoocJSONResult.ok(user.getOpen_id());
			}
			//WXSessionModel model = JsonUtils.jsonToPojo(result, WXSessionModel.class);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return IMoocJSONResult.ok();
	}

	@RequestMapping(value="/user/wxgetUserInfo",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public IMoocJSONResult wxgetUserInfo(@RequestBody String json) {
		User user = new User();
		try {
			JSONObject Obtain_id = new JSONObject(json);
			System.out.println("json："+Obtain_id);
//			System.out.println("openid: " + Obtain_id.get("openid"));		//openid 取到值
			/*参数获取开始*/
			String openid = Obtain_id.get("openId").toString();
			/*参数获取结束*/
			user = userService.getUserInfo(openid);
			if (user != null){
				userService.getUserInfo(openid);
			}
			//WXSessionModel model = JsonUtils.jsonToPojo(json, WXSessionModel.class);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return IMoocJSONResult.ok(user);
	}

	@RequestMapping(value="/user/wxsetUserInfo",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public IMoocJSONResult wxsetUserInfo(@RequestBody String json) {
		User user = new User();
		try {
			JSONObject Obtain_id = new JSONObject(json);
			System.out.println("json："+Obtain_id);
			System.out.println("openid: " + Obtain_id.get("open_id"));		//openid 取到值
			/*参数获取开始*/
			String open_id = Obtain_id.get("open_id").toString();
			String name = Obtain_id.get("name").toString();
			String phone = Obtain_id.get("phone").toString();
			String card = Obtain_id.get("card").toString();
			String address = Obtain_id.get("address").toString();
			String emergency_phone = Obtain_id.get("emergency_phone").toString();
			String emergency_name = Obtain_id.get("emergency_name").toString();
			/*参数获取结束*/
			user = userService.getUserInfo(open_id);
			if (user != null){
				User upduser = new User();
				upduser.setOpen_id(open_id);
				upduser.setPhone(phone);
				upduser.setName(name);
				upduser.setCard(card);
				upduser.setAddress(address);
				upduser.setEmergency_phone(emergency_phone);
				upduser.setEmergency_name(emergency_name);
				int upd = userService.setUserInfo(upduser);
				if (upd>0){
					System.out.println("成功");
				}
			}
			//WXSessionModel model = JsonUtils.jsonToPojo(json, WXSessionModel.class);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return IMoocJSONResult.ok(user);
	}

	
	@RequestMapping("/greet")
    public WxMpUser greetUser(String code) {
        WxMpService mpService = WxMpConfiguration.getMpServices().get("wxc6cc463dd8652f2c");
        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code);
            WxMpUser user = mpService.oauth2getUserInfo(accessToken, null);
            return user;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return null;
    }
}
